<template>
  <!-- 只有当 localMoment.avatar 有值时才渲染，防止访问未定义属性报错 -->
  <div v-if="localMoment.avatar" class="moments_list">
    <!-- 用户头像 -->
    <div class="moments_list_avatar">
      <img :src="localMoment.avatar" />
    </div>

    <!-- 右侧内容 -->
    <div class="moments_list_right">
      <!-- 用户名 -->
      <div class="list_right_show moments_list_name">{{ localMoment.nickname }}</div>

      <!-- 朋友圈文本（动态高度） -->
      <div
        class="list_right_show moments_text"
        :class="{ expanded: expandedIds.includes(localMoment.id) }"
      >
        {{ localMoment.text }}
      </div>

      <!-- 展示全文按钮 -->
      <div
        v-if="localMoment.text.length > 10"
        class="list_right_show moments_toggle"
        @click="openMore(localMoment.id)"
      >
        {{ expandedIds.includes(localMoment.id) ? '收起' : '全文' }}
      </div>

      <!-- 九宫格图片组件 -->
      <image-grid :images="localMoment.images" />

      <!-- 时间与操作按钮 -->
      <div class="list_right_show moments_time_and_action">
        <div class="moments_time">{{ localMoment.time }}</div>
        <div class="moments_and_null"></div>
        <div @click="handleLike(localMoment.id)" class="moments_action_like">喜欢</div>
        <div @click="toggleCommentBox" class="moments_action_comment">评论</div>
      </div>

      <!-- 点赞列表展示 -->
      <like-list v-if="localMoment.likes.length > 0" :likes="localMoment.likes" />

      <!-- 评论列表展示 -->
      <comment-list v-if="localMoment.comments.length > 0" :comments="localMoment.comments" />
    </div>
  </div>

  <!-- 底部固定评论输入框 -->
  <div v-if="showCommentBox" class="comment-input-bottom-fixed">
    <input
      v-model="newComment"
      class="comment-input"
      type="text"
      placeholder="写点什么..."
    />
    <button class="comment-submit-button" @click="submitComment(localMoment.id)">发送</button>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import ImageGrid from './ImageGrid.vue';
import LikeList from './LikeList.vue';
import CommentList from './CommentList.vue';
import { likeMoment, commentMoment } from '@/api/moments';

const props = defineProps({
  moment: {
    type: Object,
    default: () => ({}),
  },
});
const emit = defineEmits(['comment-success']);
const localMoment = ref({});
const expandedIds = ref<number[]>([]);
const showCommentBox = ref(false);
const newComment = ref('');
const userId = uni.getStorageSync('user_id');

const openMore = (id: number) => {
  const index = expandedIds.value.indexOf(id);
  if (index > -1) {
    expandedIds.value.splice(index, 1);
  } else {
    expandedIds.value.push(id);
  }
};

watch(
  () => props.moment,
  (newVal) => {
    localMoment.value = newVal && Object.keys(newVal).length > 0
      ? JSON.parse(JSON.stringify(newVal))
      : {};
  },
  { immediate: true }
);

const handleLike = async (momentId) => {
  try {
    const res = await likeMoment(momentId, userId);
    if (res.data.code === 200) {
      uni.showToast({ title: '点赞成功', icon: 'success' });

      // ✅ 假设你已从本地缓存中获取用户昵称
      const nickname = uni.getStorageSync('nickname') || '我';

      // 初始化 likes 数组（防止为空）
      if (!Array.isArray(localMoment.value.likes)) {
        localMoment.value.likes = [];
      }

      // 避免重复点赞（昵称不能重复）
      if (!localMoment.value.likes.includes(nickname)) {
        localMoment.value.likes.push(nickname);
      }

    } else {
      uni.showToast({ title: res.data.msg || '点赞失败', icon: 'none' });
    }
  } catch (e) {
    uni.showToast({ title: '请求出错', icon: 'none' });
  }
};


const submitComment = async (momentId) => {
  const content = newComment.value.trim();
  if (!content) return uni.showToast({ title: '请输入评论内容', icon: 'none' });

  try {
    const res = await commentMoment(momentId, userId, content);
    if (res.data.code === 200) {
      uni.showToast({ title: '评论成功', icon: 'success' });
      if (!localMoment.value.comments) localMoment.value.comments = [];
      localMoment.value.comments.push({ user: '我', content });
      newComment.value = '';
      showCommentBox.value = false;
      emit('comment-success', { momentId, comment: { user: '我', content } });
    } else {
      uni.showToast({ title: res.data.msg || '评论失败', icon: 'none' });
    }
  } catch (err) {
    console.error('评论异常：', err.message);
    uni.showToast({ title: '网络异常', icon: 'none' });
  }
};

const toggleCommentBox = () => {
  showCommentBox.value = !showCommentBox.value;
};
</script>

<style scoped>
.moments_list {
  display: flex;
  justify-content: center;
  width: 100%;
  height: auto;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
  margin-bottom: 18px;
}

.moments_list_avatar {
  width: 60px;
  height: 60px;
  margin: 8px;
}

.moments_list_avatar img {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

.moments_list_right {
  flex: 1;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.list_right_show {
  width: 100%;
}

.moments_list_name {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 6rpx;
}

.moments_text {
  max-height: 120rpx;
  overflow: hidden;
  transition: max-height 0.3s ease;
  padding-right: 20rpx; /* 添加右侧间隔 */
}

.moments_text.expanded {
  max-height: none;
}

.moments_toggle {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 8rpx;
  cursor: pointer;
}

.image-grid {
  margin-bottom: 10px;
}

.moments_time_and_action {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 40px;
  line-height: 40px;
  margin-top: 8rpx;
}

.moments_time {
  font-size: 24rpx;
  color: #999;
  text-align: right;
  margin-right: 10rpx;
}

.moments_and_null {
  flex-grow: 1;
}

.moments_action_like,
.moments_action_comment {
  font-size: 28rpx;
  color: #666;
  cursor: pointer;
  transition: color 0.3s ease;
  margin-right: 20rpx;
}

.moments_action_like:hover,
.moments_action_comment:hover {
  color: #0080ff;
}

.comment-input-bottom-fixed {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 12rpx;
  background-color: #f9f9f9;
  display: flex;
  align-items: center;
  border-top: 1px solid #eee;
  z-index: 1000;
}

.comment-input {
  flex: 1;
  height: 60rpx;
  padding: 0 16rpx;
  border: 1px solid #ccc;
  border-radius: 8rpx;
  font-size: 28rpx;
  background-color: #fff;
  margin-right: 10rpx;
}

.comment-submit-button {
  height: 60rpx;
  padding: 0 20rpx;
  background-color: #0080ff;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 28rpx;
  cursor: pointer;
}
</style>
